<?php
namespace My\Model;

use Utuo\UtuoModel;

class FormVoteModel extends UtuoModel {
	
	protected function _after_insert($data,$options) {
		$id = $data[$this->getPk()];
		$answser = I('answer');
		$pic=I('image');
		$m = M('FormVoteItem');
		$data = array();
		foreach ($answser as $k => $v) {
			$data[] = array(
				'form_vote_id' => $id,
				'answer' => $v['answer'],
				'pic'    =>$pic[$k],
				'sort' => $k,
			);
		}
		
		empty($data) or $m->addAll($data);
	}
	
	protected function _after_update($data,$options) {
		$id = $data[$this->getPk()];
		$answer = I('answer');
		$pic=I('image');
		
		$m = M('FormVoteItem');
		$ids = array();
		foreach ( $answer as $k => $v  ) { // 获得更新项
			if( !empty($v['id']) ) {
				$ids[] = $v['id'];
				$m->save(array('id' => $v['id'], 'answer' => $v['answer'],'pic'=>$pic[$k], 'sort' => $k));
				//echo M()->getLastSql();
			} else {
				$ids[] = $m->add(array('form_vote_id' => $id, 'answer' => $v['answer'],'pic'    =>$pic[$k], 'sort' => $k));
			}
		}
		$m->where(array('id'=>array('not in', $ids)))->delete(); // 删除项
	}
}